﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.Xml.XPath;

namespace TheOutfield.UmbExt.UniversalMediaPicker.Extensions
{
    /// <summary>
    /// Extension methods for exceptions.
    /// </summary>
    /// <remarks>These Exception extension methods are primarily used for the XsltExtensions methods.</remarks>
    public static class ExceptionExtensions
    {
        /// <summary>
        /// Returns the Exception message as XML.
        /// </summary>
        /// <param name="ex">The Exception object.</param>
        /// <returns>An XmlDocument of the Exception object.</returns>
        public static XmlDocument ToXml(this Exception ex)
        {
            // TODO: Serialize the Exception object. [LK]
            // ref: http://stackoverflow.com/questions/486460/how-to-serialize-an-exception-object-in-c

            XmlDocument doc = new XmlDocument();

            doc.LoadXml(String.Format("<error><![CDATA[ {0} ]]></error>", ex.Message));

            return doc;
        }

        /// <summary>
        /// Returns the Exception message as a XPathNodeIterator object.
        /// </summary>
        /// <param name="ex">The Exception object.</param>
        /// <returns>An XPathNodeIterator instance of the Exception object.</returns>
        public static XPathNodeIterator ToXPathNodeIterator(this Exception ex)
        {
            XmlDocument doc = ex.ToXml();
            return doc.CreateNavigator().Select("/error");
        }
    }

}